package com.lottery.ruok.lottrey.activity;

import android.animation.Animator;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.bumptech.glide.Glide;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.ChangLongFragmentAdapter;
import com.lottery.ruok.lottrey.adapter.ChuantongcaiGridAdapter;
import com.lottery.ruok.lottrey.adapter.MyPagerAdapter;
import com.lottery.ruok.lottrey.adapter.PrizeListAdapter;
import com.lottery.ruok.lottrey.bean.LotteryItem;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.AddBetList;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.ChangLongRefrash;
import com.lottery.ruok.lottrey.eventbusObject.GetAccountWithPush;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.PrizePushInfo;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.fragment.ChangLongFragment;
import com.lottery.ruok.lottrey.fragment.LuziFragment;
import com.lottery.ruok.lottrey.fragment.YiLouFragment;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetChatRoomCurrentStatus;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCurrentIssueNoRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetLotteryDetailRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetPrizeHistoryRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ChatRoomStatus;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCurrentIssueNoResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetLotteryDetailResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetPrizeHistroyResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.ui.BottomOrderLayout;
import com.lottery.ruok.lottrey.ui.component.BuyLotteryTopView;
import com.lottery.ruok.lottrey.ui.widget.TabSelect;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import count_down.CountDownManager;
import glideHelp.GlideHelper;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import ui.AreaCircle;
import ui.NoScrollGridView;
import utils.LogUtil;
import utils.StringUtils;
import utils.Utils;

//import ui.IToastBell;
/*
 * 传统彩票投注大厅详情页
 * 俩面长龙使用TabLayout+ViewPager+Fragment的模式，两面长龙三个接口，数据结构不同以往
 * */

public class ChuantongcaiActivity extends BaseActivity implements SensorEventListener {
    private static final int WHAT_REFRESH_TIME = 10;
    @BindView(R.id.contents)
    LinearLayout contents;
    @BindView(R.id.anim_view)
    LottieAnimationView animView;
    @BindView(R.id.start_prize)
    LinearLayout startPrize;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.dice_gif_layout)
    LinearLayout dice_gif_layout;
    @BindView(R.id.anim_prize)
    LottieAnimationView animPrize;
    @BindView(R.id.prize_list)
    ListView prizeList;
    @BindView(R.id.shadow)
    ImageView shadow;
    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.issue)
    TextView issue;
    @BindView(R.id.downtime)
    TextView downtime;
    @BindView(R.id.ball_view)
    ImageView ball_view;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.view_refresh_animation)
    LottieAnimationView viewRefreshAnimation;
    @BindView(R.id.view_refresh)
    FrameLayout viewRefresh;
    @BindView(R.id.tab_select)
    TabSelect mTabSelect;
    @BindView(R.id.ll_chuan_select1)
    LinearLayout llChuanSelect1;
    @BindView(R.id.ll_chuan_select2)
    LinearLayout llChuanSelect2;
    @BindView(R.id.tabs2)
    TabLayout tabs2;
    @BindView(R.id.viewPager2)
    ViewPager viewPager2;
    @BindView(R.id.buy_lottery_top)
    BuyLotteryTopView buyLotteryTop;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_REFRESH_TIME:
                    ivRefresh.setEnabled(true);
                    ivRefresh.setSelected(true);
                    break;
            }
        }
    };
    private ArrayList<View> mViewList = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<LotteryItem>>> lotteryItemList = new ArrayList<>();
    private ArrayList<ArrayList<ChuantongcaiGridAdapter>> chuantongcaiGridAdapterList = new ArrayList<>();
    private String currentType;
    public String currentNo;//当前期号
    private GetLotteryDetailResponse getLotteryDetailResponse;
    View include_prize_layout;
    private int moneyAndNums;
    private boolean mIsPrizeTime;//是否处于开奖状态
    private int mTipIndex = 0;//记录我切到哪个tab，对应哪个玩法提示
    public String ANALYTIC_VERSION = "1.0";
    private static final String CODE = "code";
    private BottomOrderLayout mBottomOrderLayout;
    private SensorManager mSensorManager;
    private Vibrator mVibrator;//手机震动
    private boolean isShake = false;//记录摇动状态
    private MyHandler mHandler;
    private static final int START_SHAKE = 0x1;
    private static final int AGAIN_SHAKE = 0x2;
    private static final int END_SHAKE = 0x3;
    private ArrayList<GetPrizeHistroyResponse> getPrizeHistroyResponses = new ArrayList<>();
    private CountDownManager.CountDownModel countDownModel;
    private GetCurrentIssueNoResponse data;
    private PrizeListAdapter prizeListAdapter;
    private String lotteryCode;
    private boolean isLoad=false;


    private void confirm(boolean gotoShoppingCar) {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_buy");

        if (UserInfo.getToken().equals("")) {
            gotoLoginActivity();
        } else {
            if (!mBottomOrderLayout.getMoney_and_num().getText().toString().equals("")) {
//                if (Float.parseFloat(UserInfo.getAccount()) < moneyAndNums) {
//                    Utils.showToast("您的余额不足");
//                } else {
                    ArrayList<LHCBetListActivity.Results> chooses = new ArrayList<>();
                    for (ArrayList<ArrayList<LotteryItem>> lotteryItems : lotteryItemList) {
                        for (ArrayList<LotteryItem> lotteryItemC : lotteryItems) {
                            for (LotteryItem lotteryItem : lotteryItemC) {
                                if (lotteryItem.isChoose) {
                                    LHCBetListActivity.Results result = new LHCBetListActivity.Results();
                                    result.title = lotteryItem.title + " " + lotteryItem.name;
                                    result.single = Integer.parseInt(mBottomOrderLayout.getMoney_and_num().getText().toString().equals("") ? "0" : mBottomOrderLayout.getMoney_and_num().getText().toString());
                                    result.odd = lotteryItem.odd;
                                    result.rule_id = lotteryItem.rule_id;
                                    result.number = lotteryItem.name;
                                    result.quantity = 1;
                                    result.total = result.single;
                                    if (lotteryItem.rakeback != null && !lotteryItem.rakeback.equals("")) {
                                        result.rakeback = lotteryItem.rakeback;
                                    } else {
                                        result.rakeback = "0";
                                    }

                                    chooses.add(result);
                                }
                            }
                        }
                    }

                    if (gotoShoppingCar) {
                        Intent intent = new Intent(ChuantongcaiActivity.this, LHCBetListActivity.class);
                        intent.putExtra("type", 1);//0是六合彩，1是传统彩
                        intent.putExtra("code", getIntent().getStringExtra("code"));
                        intent.putParcelableArrayListExtra("lists", chooses);
                        startActivity(intent);
                    } else {
                        delete();
                        mBottomOrderLayout.bottomShowState1();
                        LHCBetListActivity.liuheBeanArrayList.addAll(chooses);
                    }
//                }
            } else {
                Utils.showToast("请填写金额");
            }
        }
    }

    private void gotoShoppingCar() {
        if (LHCBetListActivity.liuheBeanArrayList.size() > 0) {
            Intent intent = new Intent(ChuantongcaiActivity.this, LHCBetListActivity.class);
            intent.putExtra("type", 1);//0是六合彩，1是传统彩
            intent.putExtra("code", getIntent().getStringExtra("code"));
            intent.putExtra("shopping_car", true);
            startActivity(intent);
        } else {
            Utils.showToast("目前注单为0");
        }
    }

    @OnClick({R.id.start_prize, R.id.ball_view, R.id.iv_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ball_view:
                gotoChatRoom(lotteryCode);
                break;
            case R.id.start_prize:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_recent_drawbtn");
                recentPrize();
                break;
            case R.id.iv_refresh:
                view.setEnabled(false);
                view.setSelected(false);
                view.setVisibility(View.GONE);
                handler.sendEmptyMessageDelayed(WHAT_REFRESH_TIME, 20000);
                viewRefreshAnimation.setVisibility(View.VISIBLE);
                viewRefreshAnimation.playAnimation();
                viewRefreshAnimation.addAnimatorListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        ivRefresh.setVisibility(View.VISIBLE);
                        viewRefreshAnimation.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                });
                updateAccount(new AfterUpdateAccount() {
                    @Override
                    public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                        UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                        mBottomOrderLayout.setLoginState();
                    }
                });
                break;
        }
    }


    private void delete() {
        for (ArrayList<ArrayList<LotteryItem>> lotteryItems : lotteryItemList) {
            for (ArrayList<LotteryItem> lotteryItemC : lotteryItems) {
                for (LotteryItem lotteryItem : lotteryItemC) {
                    lotteryItem.isChoose = false;
                }
            }
        }
        for (ArrayList<ChuantongcaiGridAdapter> chuantongcaiGridAdapters : chuantongcaiGridAdapterList) {
            for (ChuantongcaiGridAdapter chuantongcaiGridAdapter : chuantongcaiGridAdapters) {
                chuantongcaiGridAdapter.notifyDataSetChanged();
            }
        }
        mBottomOrderLayout.bottomShowState1();
    }

    @Override
    protected void onStart() {
        super.onStart();

        mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));//获取 SensorManager 负责管理传感器
        if (mSensorManager != null) {
            Sensor mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//获取加速度传感器
            if (mAccelerometerSensor != null) {
                mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
            }
        }
    }

    @Override
    protected void onPause() {
        if (mSensorManager != null) {// 务必要在pause中注销 mSensorManager,否则会造成界面退出后摇一摇依旧生效的bug
            mSensorManager.unregisterListener(this);
        }

        super.onPause();
    }


    private void handlePrizeData() {
        if (getPrizeHistroyResponses.size() > 0) {
            String[] p = getPrizeHistroyResponses.get(0).getPrize_num().split(",");
            if (p.length > 0 && !p[0].equals("")) {
                container.removeAllViews();
                for (String s : p) {
                    if (Common.isK3(currentType)) {
                        ImageView dice = new ImageView(this);
                        dice.setImageResource(Common.getDiceDrawable(StringUtils.parseInt(s)));
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 24), Utils.dip2px(this, 24));
                        layoutParams.rightMargin = Utils.dip2px(this, 11);
                        dice.setLayoutParams(layoutParams);
                        container.addView(dice);
                    } else {
                        AreaCircle areaCircle = new AreaCircle(ChuantongcaiActivity.this);
                        Common.setBallBackground(areaCircle, s, currentType);
                        areaCircle.setText(s);
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(ChuantongcaiActivity.this, 24), Utils.dip2px(ChuantongcaiActivity.this, 24));
                        layoutParams.rightMargin = Utils.dip2px(ChuantongcaiActivity.this, 11);
                        areaCircle.setLayoutParams(layoutParams);
                        container.addView(areaCircle);
                    }

                }
                if (prizeList.getVisibility() != View.VISIBLE) {
                    container.setVisibility(View.VISIBLE);
                    if (Common.isK3(lotteryCode)) {
                        dice_gif_layout.setVisibility(View.GONE);
                    } else {
                        animPrize.setVisibility(View.GONE);
                        animPrize.pauseAnimation();
                    }
                    //发送更新的eventbus
                    EventBus.getDefault().post(new ChangLongRefrash());
                }
                mIsPrizeTime = false;

            } else {
                setPrizeState();
            }
            if (prizeListAdapter == null) {
                prizeListAdapter = new PrizeListAdapter(getPrizeHistroyResponses, ChuantongcaiActivity.this, getIntent().getStringExtra("code"), mIsPrizeTime);
                prizeList.setAdapter(prizeListAdapter);
            } else {
                prizeListAdapter.setData(getPrizeHistroyResponses, getIntent().getStringExtra("code"), mIsPrizeTime);
            }
        }
    }

    private void getPrizeHistory() {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetPrizeHistoryRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<ArrayList<GetPrizeHistroyResponse>>handleResultReConnection())
                .subscribeWith(new RxSubscribe<ArrayList<GetPrizeHistroyResponse>>(this) {
                    @Override
                    protected void _onNext(ArrayList<GetPrizeHistroyResponse> g) {
                        getPrizeHistroyResponses.clear();
                        getPrizeHistroyResponses.addAll(g);

                        handlePrizeData();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
        disposables.add(disposableObserver);
    }

    private void setPrizeState() {
        if (prizeList.getVisibility() != View.VISIBLE) {
            container.setVisibility(View.GONE);
            if (Common.isK3(lotteryCode)) {
                dice_gif_layout.setVisibility(View.VISIBLE);
            } else {
                animPrize.setVisibility(View.VISIBLE);
                animPrize.resumeAnimation();
            }

        }
        mIsPrizeTime = true;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initExtral();
        setContentView(R.layout.activity_chuantongcai);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
        if (getIntent() != null) {
            lotteryCode = getIntent().getStringExtra("code");
        }
     /*   //传统江苏快3    ctjiangsuk3    无漏子 单球 及两面
        if (lotteryCode.equals("ctjiangsuk3")) {
            mTabSelect.setVisibility(View.GONE);
        }
        //极速快3    jsk3    无漏子 单球 及两面
        if (lotteryCode.equals("jsk3")) {
            mTabSelect.setVisibility(View.GONE);
        }*/
        init();
        countDown();
        if (Utils.isEmpty(UserInfo.getToken())) {
            //未登录
            viewRefresh.setVisibility(View.GONE);
            viewRefresh.setSelected(false);
        } else {
            viewRefresh.setVisibility(View.VISIBLE);
            viewRefresh.setSelected(true);
        }
        buyLotteryTop.setBuyLotteryTopViewListener(new BuyLotteryTopView.BuyLotteryTopViewListener() {
            @Override
            public void tabOnClick(int type) {
                switch (type) {
                    //1back，2彩票名称，3投注记录，4走势，5规则
                    case 1:
                        finish();
                        break;
                    case 2:
                        ChooseLotteryActivity.startActivity(ChuantongcaiActivity.this, currentType);
                        break;
                    case 3:
                        gotoOrderList();
                        break;
                    case 4:
                        gotoPrizeList();
                        break;
                    case 5:
                        gotoRule();
                        break;

                }
            }
        });

        getRoomStatus();
        if (UserInfo.getChatStatus() == ChatRoomStatus.CHAT_ROOM_STATUS_OPEN) {
            ball_view.setVisibility(View.VISIBLE);
        } else if (UserInfo.getChatStatus() == ChatRoomStatus.CHAT_ROOM_STATUS_CLOSE) {
            ball_view.setVisibility(View.GONE);
        }

//        getRoomStatus();
        //两面长龙模块
        initChangLong();
    }

    private void initChangLong() {
        ArrayList<String> titleDatas = new ArrayList<>();
        if (Common.isK3(lotteryCode)) {
            titleDatas.add("遗漏");
        } else {
            titleDatas.add("路子");
            titleDatas.add("两面长龙");
            titleDatas.add("遗漏");
        }
        ArrayList<android.support.v4.app.Fragment> fragmentList = new ArrayList<>();
        if (Common.isK3(lotteryCode)) {
            fragmentList.add(new YiLouFragment());
        } else {
            fragmentList.add(new LuziFragment());
            fragmentList.add(new ChangLongFragment());
            fragmentList.add(new YiLouFragment());
        }


        final ChangLongFragmentAdapter changLongFragmentAdapter = new ChangLongFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager2.setAdapter(changLongFragmentAdapter);
        tabs2.setupWithViewPager(viewPager2);
        viewPager2.setOffscreenPageLimit(3);
        tabs2.setTabsFromPagerAdapter(changLongFragmentAdapter);
        for (int i = 0; i < changLongFragmentAdapter.getCount(); i++) {
            TabLayout.Tab tab = tabs2.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(titleDatas.get(i), i));
            }
        }
        viewPager2.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < changLongFragmentAdapter.getCount(); i++) {
                    if (i == position) {
                        tabs2.getTabAt(i).getCustomView().findViewById(R.id.imageView).setVisibility(View.VISIBLE);
                    } else {
                        tabs2.getTabAt(i).getCustomView().findViewById(R.id.imageView).setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void countDown() {
        countDownModel = new CountDownManager.CountDownModel() {
            @Override
            public void onExecute() {
                if (data != null) {
                    data.setTime(data.getTime() - 1);
                    if (data.getTime() >= 0) {
                        String timeText=Utils.getCountTimeByLong(data.getTime() * 1000);
                        downtime.setText(timeText);
                        if (Utils.isFengg(timeText)) {
                            if (isLoad){
                                isFeng(true);
                            }

                        }
                    } else {
                        if (!mIsPrizeTime) {
                            mIsPrizeTime = true;
                            GetPrizeHistroyResponse item = new GetPrizeHistroyResponse();
                            item.setIssue_no(currentNo);
                            item.setPrize_num("");
                            getPrizeHistroyResponses.add(0, item);
                            handlePrizeData();
                            setTimer();
                            setPrizeState();
                        }
                    }
                }
            }
        };


        CountDownManager.asInstance().register(countDownModel);

    }

    private void isFeng(boolean isFeng) {
            for (ArrayList<ArrayList<LotteryItem>> lotteryItems : lotteryItemList) {
                for (ArrayList<LotteryItem> lotteryItemC : lotteryItems) {
                    for (LotteryItem lotteryItem : lotteryItemC) {
                        lotteryItem.isFen = isFeng;
                    }
                }
            }
            for (ArrayList<ChuantongcaiGridAdapter> chuantongcaiGridAdapters : chuantongcaiGridAdapterList) {
                for (ChuantongcaiGridAdapter chuantongcaiGridAdapter : chuantongcaiGridAdapters) {
                    chuantongcaiGridAdapter.notifyDataSetChanged();
                }
            }
            if (isFeng) {
                mBottomOrderLayout.bottomShowState1();
                setMoneyClear();
            }

    }

    private void setMoneyClear() {
        for (ArrayList<ArrayList<LotteryItem>> lists : lotteryItemList) {
            for (ArrayList<LotteryItem> arrayList : lists) {
                for (LotteryItem item : arrayList) {
                   item.isChoose=false;
                }
            }
        }
        int sum = 0;

        int money_per_note;
        if (!mBottomOrderLayout.getMoney_and_num().getText().toString().equals("")) {
            money_per_note = Integer.parseInt(mBottomOrderLayout.getMoney_and_num().getText().toString());
        } else {
            money_per_note = 0;
        }
        moneyAndNums = money_per_note * sum;
        mBottomOrderLayout.getNumAndMoney().setText(sum + "注" + moneyAndNums + "元");
    }

    private void initExtral() {
        Intent intent = getIntent();
        currentType = intent.getStringExtra(CODE);
    }

    @Override
    protected void onDestroy() {
        CountDownManager.asInstance().register(countDownModel);
        EventBus.getDefault().unregister(this);

        super.onDestroy();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        mBottomOrderLayout.setLoginState();

        getRedPacketNum(ball_view);
        if (Utils.isEmpty(UserInfo.getToken())) {
            //未登录
            viewRefresh.setVisibility(View.GONE);
            viewRefresh.setSelected(false);
        } else {
            viewRefresh.setVisibility(View.VISIBLE);
            viewRefresh.setSelected(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(AddBetList addBetList) {
        delete();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetAccountWithPush getAccountWithPush) {
        mBottomOrderLayout.setLoginState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrizePushInfo event) {
        if (event.getCode() != null && getIntent().getStringExtra("code") != null) {
            if (("ct" + event.getCode()).equals(getIntent().getStringExtra("code")) || event.getCode().equals(getIntent().getStringExtra("code"))) {
                if (event.getIssueNo() != null) {
                    if (getPrizeHistroyResponses.size() > 0 && Utils.isEmpty(getPrizeHistroyResponses.get(0).getPrize_num())) {
                        getPrizeHistroyResponses.get(0).setIssue_no(event.getIssueNo());
                        getPrizeHistroyResponses.get(0).setPrize_num(event.getPrizeNum());
                        mIsPrizeTime = false;
                        handlePrizeData();
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartPrzePush event) {
        setTimer();
        getPrizeHistory();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(AddBetSuccess addBetSuccess) {
        if (addBetSuccess.getAfter_amount() != null) {
            UserInfo.setAccount(addBetSuccess.getAfter_amount());
            mBottomOrderLayout.setLoginState();
        } else {
            updateAccount(new AfterUpdateAccount() {
                @Override
                public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                    UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                    mBottomOrderLayout.setLoginState();
                }
            });
        }

        delete();
    }

    private void setMoney() {
        int sum = 0;
        for (ArrayList<ArrayList<LotteryItem>> lists : lotteryItemList) {
            for (ArrayList<LotteryItem> arrayList : lists) {
                for (LotteryItem item : arrayList) {
                    if (item.isChoose) {
                        sum++;
                    }
                }
            }
        }
        int money_per_note;
        if (!mBottomOrderLayout.getMoney_and_num().getText().toString().equals("")) {
            money_per_note = Integer.parseInt(mBottomOrderLayout.getMoney_and_num().getText().toString());
        } else {
            money_per_note = 0;
        }
        moneyAndNums = money_per_note * sum;
        mBottomOrderLayout.getNumAndMoney().setText(sum + "注" + moneyAndNums + "元");
        mBottomOrderLayout.bottomShowState2();
    }

    private void init() {
        initPrizeAnimal();
        getRedPacketNum(ball_view);
        Disposable observer = LHCBetListActivity.liuheBeanArrayList.getObservable().subscribe(new Consumer<ArrayList<LHCBetListActivity.Results>>() {
            @Override
            public void accept(final ArrayList<LHCBetListActivity.Results> results) {
                mBottomOrderLayout.getInclude_note_count().setText(results.size() + "");
            }
        });
        disposables.add(observer);

        mHandler = new MyHandler(this);
        //获取Vibrator震动服务
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        mBottomOrderLayout = new BottomOrderLayout(this,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        if (!Utils.isFastDoubleClick()) {
                            startShake();
                        }
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        delete();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        setMoney();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        confirm(true);
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        gotoShoppingCar();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        confirm(false);
                        return null;
                    }
                }, false,
                null,
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        gotoLoginActivity();
                        return null;
                    }
                },
                new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
//                        gotoSummaryActivity();
                        startActivity(new Intent(ChuantongcaiActivity.this, OrderActivity.class));
                        return null;
                    }
                });

        include_prize_layout = findViewById(R.id.include_prize_layout);

        setTimer();

        getPrizeHistory();

        getLotteryDetail(true);

        mTabSelect.setTabSelectListener(new TabSelect.TabSelectListener() {
            @Override
            public void tabOnClick(int selected) {
                switch (selected) {
                    case TabSelect.TabSelectListener.SELECT_TAB1:
                        llChuanSelect2.setVisibility(View.GONE);
                        llChuanSelect1.setVisibility(View.VISIBLE);
                        //IToast.show("普通模式",ChuantongcaiActivity.this);
                        isShake = false;
                        break;
                    case TabSelect.TabSelectListener.SELECT_TAB2:
                        llChuanSelect1.setVisibility(View.GONE);
                        llChuanSelect2.setVisibility(View.VISIBLE);
                        // IToast.show("长龙遗漏模式",ChuantongcaiActivity.this);
                        isShake = true;
                        break;
                }
            }
        });
    }

    private void initPrizeAnimal() {
        if (Common.isK3(lotteryCode)) {
            animPrize.setVisibility(View.GONE);
            for (int i = 0; i < 3; i++) {
                ImageView dice = new ImageView(this);
                Glide.with(this).load(R.drawable.dice).asGif().into(dice);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(this, 25), Utils.dip2px(this, 25));
                layoutParams.rightMargin = Utils.dip2px(this, 11);
                dice.setLayoutParams(layoutParams);
                dice_gif_layout.addView(dice);
            }
            dice_gif_layout.setVisibility(View.VISIBLE);
        } else {
            dice_gif_layout.setVisibility(View.GONE);
            animPrize.setVisibility(View.VISIBLE);
        }
    }

    private void getLotteryDetail(final boolean progress) {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetLotteryDetailRequest.class).getResult(getIntent().getStringExtra("code"), UserInfo.getToken())
                .compose(RxHelper.<GetLotteryDetailResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetLotteryDetailResponse>(this) {

                    @Override
                    protected void _onNext(GetLotteryDetailResponse g) {
                        getLotteryDetailResponse = g;

                        if (getLotteryDetailResponse != null && getLotteryDetailResponse.getRemaining_balance() != null) {
                            if (!UserInfo.getToken().equals("")) {
                                UserInfo.setAccount(getLotteryDetailResponse.getRemaining_balance());
                                mBottomOrderLayout.setLoginState();
                            }
                        }
                        buyLotteryTop.setLotteryName(getLotteryDetailResponse.getName());
                        if (getLotteryDetailResponse.getLayouts().size() <= 4) {
                            tabs.setTabMode(TabLayout.MODE_FIXED);
                        } else {
                            tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
                        }
                        for (int i = 0; i < getLotteryDetailResponse.getLayouts().size(); i++) {
                            View view = getLayoutInflater().inflate(R.layout.custom_tab_chuantong, null);
                            mViewList.add(view);

                            final LinearLayout listView = view.findViewById(R.id.listview);

                            //如果存在childrenBeanX.getMax_odds()大于1的情况，那么生成title
                            boolean hasTitle = false;
                            for (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX childrenBeanX : getLotteryDetailResponse.getLayouts().get(i).getChildren()) {
                                if (childrenBeanX.getMax_odds() != null && childrenBeanX.getMax_odds().size() > 1) {
                                    hasTitle = true;
                                }
                            }
                            ArrayList<ArrayList<LotteryItem>> arrayLists = new ArrayList();
                            for (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX childrenBeanX : getLotteryDetailResponse.getLayouts().get(i).getChildren()) {
                                if (childrenBeanX.getMax_odds() != null) {
                                    if (childrenBeanX.getMax_odds().size() > 1) {
                                        int sum = 0;
                                        ArrayList<LotteryItem> lotteryItems = new ArrayList();
                                        for (Object o : childrenBeanX.getMax_odds().keySet()) {
                                            LotteryItem lotteryItem = new LotteryItem();
                                            if (sum == 0) {
                                                lotteryItem.isFirst = true;
                                            }
                                            lotteryItem.title = childrenBeanX.getName();
                                            lotteryItem.name = o.toString();
                                            lotteryItem.rule_id = childrenBeanX.getRule_id();
                                            lotteryItem.odd = childrenBeanX.getMax_odds().get(o).toString();
                                            lotteryItem.rakeback = childrenBeanX.getMax_rakeback();
                                            sum++;
                                            lotteryItems.add(lotteryItem);
                                        }
                                        arrayLists.add(lotteryItems);
                                    } else {
                                        if (!((getLotteryDetailResponse.getLayouts().get(i).getName().contains("一")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("二")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("三")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("四")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("五")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("六")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("七")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("八")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("九")
                                                || getLotteryDetailResponse.getLayouts().get(i).getName().contains("十")) && childrenBeanX.getName().contains("总和"))) {//这种情况过滤
                                            ArrayList<LotteryItem> lotteryItems = new ArrayList();
                                            LotteryItem lotteryItem = new LotteryItem();
                                            if (hasTitle) {
                                                lotteryItem.isFirst = true;
                                            }
                                            lotteryItem.title = childrenBeanX.getName();
                                            lotteryItem.name = childrenBeanX.getName();
                                            lotteryItem.rule_id = childrenBeanX.getRule_id();
                                            for (Object key : childrenBeanX.getMax_odds().keySet()) {
                                                if (lotteryItem.odd == null) {
                                                    lotteryItem.odd = childrenBeanX.getMax_odds().get(key).toString();
                                                } else {
                                                    lotteryItem.odd = lotteryItem.odd + "," + childrenBeanX.getMax_odds().get(key).toString();
                                                }
                                            }
                                            lotteryItem.rakeback = childrenBeanX.getMax_rakeback();
                                            lotteryItems.add(lotteryItem);
                                            arrayLists.add(lotteryItems);
                                        }
                                    }
                                } else {
                                    int sum = 0;
                                    ArrayList<LotteryItem> lotteryItems = new ArrayList();
                                    if (childrenBeanX.getChildren() != null) {
                                        for (GetLotteryDetailResponse.LayoutsBean.ChildrenBeanX.ChildrenBean childrenBean : childrenBeanX.getChildren()) {
                                            LotteryItem lotteryItem = new LotteryItem();
                                            lotteryItem.name = childrenBean.getName();
                                            if (childrenBean.getMax_odds() != null) {
                                                for (Object key : childrenBean.getMax_odds().keySet()) {
                                                    if (lotteryItem.odd == null) {
                                                        lotteryItem.odd = childrenBean.getMax_odds().get(key).toString();
                                                    } else {
                                                        lotteryItem.odd = lotteryItem.odd + "," + childrenBean.getMax_odds().get(key).toString();
                                                    }
                                                }
                                            } else {
                                                continue;
                                            }
                                            lotteryItem.rakeback = childrenBean.getMax_rakeback();
                                            if (sum == 0) {
                                                lotteryItem.isFirst = true;
                                            }
                                            lotteryItem.rule_id = childrenBean.getRule_id();
                                            lotteryItem.title = childrenBeanX.getName();
                                            sum++;
                                            lotteryItems.add(lotteryItem);
                                        }
                                    }
                                    arrayLists.add(lotteryItems);
                                }
                            }

                            ArrayList<ChuantongcaiGridAdapter> cList = new ArrayList<>();
                            for (final ArrayList<LotteryItem> items : arrayLists) {
                                View views = LayoutInflater.from(ChuantongcaiActivity.this).inflate(R.layout.chuantong_item, null);
                                TextView textView = views.findViewById(R.id.title);
                                final NoScrollGridView types = views.findViewById(R.id.types);
                                String code = getIntent().getStringExtra("code");
                                if (items.size() > 0) {
                                    String name = items.get(0).title;
                                    textView.setText(name);
                                    Common.setGridAttributes(types, code, name);
                                }

                                final ChuantongcaiGridAdapter gridAdapter = new ChuantongcaiGridAdapter(items, ChuantongcaiActivity.this, new ChuantongcaiGridAdapter.ClickInterface() {
                                    @Override
                                    public void click() {
                                        setMoney();
                                    }
                                }, code);

                                types.setAdapter(gridAdapter);
                                listView.addView(views);
                                cList.add(gridAdapter);
                            }
                            chuantongcaiGridAdapterList.add(cList);
                            lotteryItemList.add(arrayLists);
                        }

                        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
                        viewPager.setAdapter(mAdapter);
                        tabs.setupWithViewPager(viewPager);

                        for (int i = 0; i < tabs.getTabCount(); i++) {
                            TabLayout.Tab tab = tabs.getTabAt(i);
                            if (tab != null) {
                                tab.setCustomView(getTabView(getLotteryDetailResponse.getLayouts().get(i).getName(), i));
                            }
                        }

                        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                            }

                            @Override
                            public void onPageSelected(int position) {
                                mTipIndex = position;

                                for (int i = 0; i < tabs.getTabCount(); i++) {
                                    if (i == position) {
                                        tabs.getTabAt(i).getCustomView().findViewById(R.id.imageView).setVisibility(View.VISIBLE);
                                    } else {
                                        tabs.getTabAt(i).getCustomView().findViewById(R.id.imageView).setVisibility(View.GONE);
                                    }
                                }
                            }

                            @Override
                            public void onPageScrollStateChanged(int state) {

                            }
                        });
                        isLoad=true;
                    }

                    @Override
                    protected boolean showDialog() {
                        return progress;
                    }
                });
        disposables.add(disposableObserver);
    }

    private View getTabView(String s, int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item, null);
        TextView tv = view.findViewById(R.id.textView);
        tv.setText(s);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        if (position == 0) {
            view.findViewById(R.id.imageView).setVisibility(View.VISIBLE);
        }
        return view;
    }

    private void setTimer() {
        RetrofitBase.getRetrofit().create(GetCurrentIssueNoRequest.class).getResult(getIntent().getStringExtra("code"))
                .compose(RxHelper.<GetCurrentIssueNoResponse>handleResultReConnection())
                .subscribe(new RxSubscribe<GetCurrentIssueNoResponse>(this) {


                    @Override
                    protected void _onNext(final GetCurrentIssueNoResponse getCurrentIssueNoResponse) {
                        ChuantongcaiActivity.this.data = getCurrentIssueNoResponse;
                        currentNo = getCurrentIssueNoResponse.getNo();

                        String year = Utils.toYear(System.currentTimeMillis());
                        if (getCurrentIssueNoResponse.getNo().startsWith(year)) {
                            issue.setText("距" + getCurrentIssueNoResponse.getNo().substring(4) + "期开奖");
                        } else {
                            issue.setText("距" + getCurrentIssueNoResponse.getNo() + "期开奖");
                        }
                        if (isLoad){
                            isFeng(false);
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }

                });
    }

    @Override
    public void finish() {
        super.finish();

        LHCBetListActivity.liuheBeanArrayList.clear();
    }

    public void gotoOrderList() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_betrecord_jump");

        if (!UserInfo.getToken().equals("")) {
            startActivity(new Intent(ChuantongcaiActivity.this, OrderActivity.class));
        } else {
            gotoLoginActivity();
        }
    }

    public void gotoPrizeList() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_numdistributing_jump");

        Intent intent = new Intent(ChuantongcaiActivity.this, PrizeListActivity.class);
        intent.putExtra("code", getIntent().getStringExtra("code"));
        intent.putExtra("isFromDetail", true);
        startActivity(intent);
    }

    public void recentPrize() {
        if (container.getVisibility() == View.VISIBLE || animPrize.getVisibility() == View.VISIBLE || dice_gif_layout.getVisibility() == View.VISIBLE) {
//            shadow.setVisibility(View.VISIBLE);
            container.setVisibility(View.GONE);
            dice_gif_layout.setVisibility(View.GONE);
            animPrize.setVisibility(View.GONE);
            animPrize.pauseAnimation();

            prizeList.setVisibility(View.VISIBLE);
            animView.setAnimation("xia.json");
            animView.playAnimation();
        } else {
//            shadow.setVisibility(View.GONE);
            if (mIsPrizeTime) {
                if (Common.isK3(lotteryCode)) {
                    dice_gif_layout.setVisibility(View.VISIBLE);
                } else {
                    animPrize.setVisibility(View.VISIBLE);
                    animPrize.resumeAnimation();
                }
            } else {
                container.setVisibility(View.VISIBLE);
            }

            prizeList.setVisibility(View.GONE);
            animView.setAnimation("shang.json");
            animView.playAnimation();
        }
    }

    public void gotoRule() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_lotteryrule_jump");

        Intent intent = new Intent(ChuantongcaiActivity.this, PlayRuleActivity.class);
        intent.putExtra("code", getIntent().getStringExtra("code"));
        startActivity(intent);
    }

    public void gotoPlayTip() {
        //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_" + getIntent().getStringExtra("code") + "_itemdetail_playmethod_jump");

        if (getLotteryDetailResponse != null && getLotteryDetailResponse.getLayouts() != null && getLotteryDetailResponse.getLayouts().get(mTipIndex) != null && getLotteryDetailResponse.getLayouts().get(mTipIndex).getTips() != null) {
            Intent intent = new Intent(ChuantongcaiActivity.this, PlayTipActivity.class);
            intent.putExtra("tips", getLotteryDetailResponse.getLayouts().get(mTipIndex).getTips());
            startActivity(intent);
        }
    }

    private void createOneBet() {//在当前tab选择一项
        if (lotteryItemList != null && mTipIndex < lotteryItemList.size() && mTipIndex >= 0 && lotteryItemList.get(mTipIndex) != null) {
            int tabIndex = Utils.getRandom(0, lotteryItemList.get(mTipIndex).size());
            if (lotteryItemList.get(mTipIndex).get(tabIndex) != null) {
                if (mViewList != null) {
                    int height = 0;
                    for (int i = 1; i < tabIndex + 1; i++) {
                        height += ((LinearLayout) (mViewList.get(mTipIndex)).findViewById(R.id.listview)).getChildAt(i - 1).getMeasuredHeight();
                    }
                    mViewList.get(mTipIndex).scrollTo(0, height);
                    int itemIndex = Utils.getRandom(0, lotteryItemList.get(mTipIndex).get(tabIndex).size());
                    lotteryItemList.get(mTipIndex).get(tabIndex).get(itemIndex).isChoose = true;
                    chuantongcaiGridAdapterList.get(mTipIndex).get(tabIndex).notifyDataSetChanged();

                    setMoney();
                }
            }
        }
    }

    static final int UPDATE_INTERVAL = 100;
    /**
     * 上一次检测的时间
     */
    long mLastUpdateTime;
    /**
     * 上一次检测时，加速度在x、y、z方向上的分量，用于和当前加速度比较求差。
     */
    float mLastX, mLastY, mLastZ;

    /**
     * 摇晃检测阈值，决定了对摇晃的敏感程度，越小越敏感。
     */
    public int shakeThreshold = 3500;

    @Override
    public void onSensorChanged(SensorEvent event) {
        int type = event.sensor.getType();

        if (type == Sensor.TYPE_ACCELEROMETER) {
            long currentTime = System.currentTimeMillis();
            long diffTime = currentTime - mLastUpdateTime;
            if (diffTime < UPDATE_INTERVAL) {
                return;
            }
            mLastUpdateTime = currentTime;
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];
            float deltaX = x - mLastX;
            float deltaY = y - mLastY;
            float deltaZ = z - mLastZ;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            float delta = (float) (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / diffTime * 10000);
            if (delta > shakeThreshold && !isShake) {// 当加速度的差值大于指定的阈值，认为这是一个摇晃
                startShake();
            }
        }
    }

    private void startShake() {
        if (mBottomOrderLayout.getInclude_state1().getVisibility() == View.VISIBLE) {
            isShake = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        //开始震动 发出提示音 展示动画效果
                        mHandler.obtainMessage(START_SHAKE).sendToTarget();
                        Thread.sleep(500);
                        //再来一次震动提示
                        mHandler.obtainMessage(AGAIN_SHAKE).sendToTarget();
                        Thread.sleep(500);
                        mHandler.obtainMessage(END_SHAKE).sendToTarget();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }

    private static class MyHandler extends Handler {
        private WeakReference<ChuantongcaiActivity> mReference;
        private ChuantongcaiActivity mActivity;

        public MyHandler(ChuantongcaiActivity activity) {
            mReference = new WeakReference(activity);
            if (mReference != null) {
                mActivity = mReference.get();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case START_SHAKE:
                    mActivity.mVibrator.vibrate(300);
                    break;
                case AGAIN_SHAKE:
                    mActivity.mVibrator.vibrate(300);
                    break;
                case END_SHAKE:
                    if (mActivity != null) {//整体效果结束, 将震动设置为false
                        mActivity.isShake = false;
                        mActivity.createOneBet();//产生一注
                    }
                    break;
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case ChooseLotteryActivity.REPONSE_CODE:
                if (data != null) {
                    String code = data.getStringExtra("code");
                    int item_class = data.getIntExtra("item_class", -1);
                    if (!Utils.isEmpty(code) && item_class != -1) {
                        gotoLotteryDetailActivity(code, item_class);
                        finish();
                    }
                }
                break;
        }
    }


    public void gotoLotteryDetailActivity(String code, int index) {//0 其它 1官方2六合3传统
        switch (index) {
            case 1: {
                Intent intent = new Intent(ChuantongcaiActivity.this, OfficalLotteryDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 2: {
                Intent intent = new Intent(ChuantongcaiActivity.this, LiuhecaiDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 3: {
                Intent intent = new Intent(ChuantongcaiActivity.this, ChuantongcaiActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
        }
    }


    /**
     * 获取运营商聊天室开关状态
     */
    public void getRoomStatus() {
        RetrofitBase.getRetrofit().create(GetChatRoomCurrentStatus.class).getResult()
                .compose(RxHelper.<ChatRoomStatus>handleResultReConnection())
                .subscribe(new RxSubscribe<ChatRoomStatus>(this) {
                    @Override
                    protected void _onNext(ChatRoomStatus chatRoomStatus) {
                        if (chatRoomStatus != null) {
                            ChatRoomStatus.DataBean data = chatRoomStatus.getData();
                            if (data != null) {
                                switch (data.getStatus()) {
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_OPEN:
                                        ball_view.setVisibility(View.VISIBLE);
                                        break;
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_CLOSE:
                                        ball_view.setVisibility(View.GONE);
                                        break;
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

}